import {Divider, Popconfirm, Table, Button, Select, Input, InputNumber, message} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import React, {useState, useEffect} from 'react'
import styles from "@/pages/Info/Edit/style.less";
import {connect} from 'umi'
import { securityTypeList, formatTypeList } from '@/utils/constant'
import { delSecurityItemPlan } from '../../service'

const {Option} = Select;

const TableForm = ({ onChange, initData = [] }) => {
  const [clickedCancel, setClickedCancel] = useState(false);
  const [loading, setLoading] = useState(false);
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [index, setIndex] = useState(0);

  const columns = [
    {
      title: '缴纳项目',
      dataIndex: 'securityType',
      key: 'securityType',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" getPopupContainer={() => document.getElementById('area')} value={text}
                    onChange={(e) => handleFieldChange(e, 'securityType', record.key)}>
              {securityTypeList.map((item, index) => {
                return (
                  <Option value={item.value} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = securityTypeList.find((item) => item.value === text)
        return res ? res.label : text
      },
    },
    {
      title: '基数下限',
      dataIndex: 'lowerLimit',
      key: 'lowerLimit',
      render: (text, record) => {
        if (record.editable) {
          return (
            <InputNumber type={"number"} value={text} min={0}
                         onChange={(e) => handleFieldChange(e, 'lowerLimit', record.key)}
            />
          )
        }
        return text
      },
    },
    {
      title: '基数上限',
      dataIndex: 'upperLimit',
      key: 'upperLimit',
      render: (text, record) => {
        if (record.editable) {
          return (
            <InputNumber type={"number"} value={text} min={0}
                         onChange={(e) => handleFieldChange(e, 'upperLimit', record.key)}
            />
          )
        }
        return text
      },
    },
    {
      title: '公司缴纳比例',
      dataIndex: 'orgRate',
      key: 'orgRate',
      render: (text, record) => {
        if (record.editable) {
          let rowData = getRowByKey(record.key, initData);
          return (
            <InputNumber
              disabled={rowData.orgFixedAmount!== undefined && rowData.orgFixedAmount!== null}
              defaultValue={text} min={0} max={100} formatter={text => `${text}%`}
              parser={text => text.replace('%', '')}
              onChange={(e) => handleFieldChange(e, 'orgRate', record.key)}
            />
          )
        }
        return text ? `${text}%` : ''
      },
    },
    {
      title: '个人缴纳比例',
      dataIndex: 'personalRate',
      key: 'personalRate',
      render: (text, record) => {
        if (record.editable) {
          let rowData = getRowByKey(record.key, initData);
          return (
            <InputNumber
              disabled={rowData.personalFixedAmount!== undefined && rowData.personalFixedAmount!== null}
              defaultValue={text} min={0} max={100} formatter={text => `${text}%`}
              parser={text => text.replace('%', '')}
              onChange={(e) => handleFieldChange(e, 'personalRate', record.key)}
            />
          )
        }
        return text ? `${text}%` : ''
      },
    },
    {
      title: '公司固定金额',
      dataIndex: 'orgFixedAmount',
      key: 'orgFixedAmount',
      render: (text, record) => {
        if (record.editable) {
          let rowData = getRowByKey(record.key, initData);
          return (
            <InputNumber disabled={rowData.orgRate!== undefined && rowData.orgRate!== null} value={text} min={0}
                         onChange={(e) => handleFieldChange(e, 'orgFixedAmount', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '个人固定金额',
      dataIndex: 'personalFixedAmount',
      key: 'personalFixedAmount',
      render: (text, record) => {
        if (record.editable) {
          let rowData = getRowByKey(record.key, initData);
          return (
            <InputNumber disabled={rowData.personalRate!== undefined && rowData.personalRate!== null} value={text} min={0}
                         onChange={(e) => handleFieldChange(e, 'personalFixedAmount', record.key)} />
          )
        }
        return text
      },
    },
    {
      title: '公司取整归零',
      dataIndex: 'orgFormat',
      key: 'orgFormat',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text} onChange={(e) => handleFieldChange(e, 'orgFormat', record.key)}>
              {formatTypeList.map((item, index) => {
                return (
                  <Option value={item.value} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = formatTypeList.find((item) => item.value === text)
        return res ? res.label : text
      },
    },
    {
      title: '个人取整归零',
      dataIndex: 'personalFormat',
      key: 'personalFormat',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text} onChange={(e) => handleFieldChange(e, 'personalFormat', record.key)}>
              {formatTypeList.map((item, index) => {
                return (
                  <Option value={item.value} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = formatTypeList.find((item) => item.value === text)
        return res ? res.label : text
      },
    },
    {
      title: '操作',
      key: 'action',
      width: '160px',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }
        if (record.editable) {
          return (
            <span>
              <a onClick={(e) => updateRow(e, record.key, record.oid)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.key)}>取消</a>
            </span>
          )
        }
        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否要删除此行？" cancelText='取消' okText='确认' onConfirm={(e) => remove(e, record.key)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      },
    },
  ];

  const getRowByKey = (key, newData) => (newData || initData)?.filter((item) => item.key === key)[0];

  const toggleEditable = (e, key) => {
    e.preventDefault();
    const newData = initData?.map((item) => ({...item}));
    const target = getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = {...target};
        setCacheOriginData(cacheOriginData)
      }
      target.editable = !target.editable;
      onChange(newData);
    }
  }

  const remove = (e, key) => {
    let deleteItem = initData.find(item => item.key === key);
    let datas = initData.filter(item => item.key !== key);
    if (deleteItem.securityItemId){
      setLoading(true);
      delSecurityItemPlan(deleteItem.securityItemId).then(res =>{
        if (res.flag){
          message.success('方案子项删除成功！');
          onChange(datas);
        }else {
          message.error(res.error);
        }
        setLoading(false);
      })
    }else {
      onChange(datas);
    }
  }

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...initData];
    const target = getRowByKey(key, newData);
    if (target) {
      if (fieldName==='orgRate' || fieldName==='personalRate'){
        target.isFixed = 0;
      }else if (fieldName==='orgFixedAmount' || fieldName==='personalFixedAmount'){
        target.isFixed = 1;
      }
      target[fieldName] = e && e.target ? e.target.value : e;
      onChange(newData);
    }
  }

  const updateRow = (e, rowKey, oid) => {
    e.persist();
    if (clickedCancel) {
      setClickedCancel(false);
      return
    }
    const target = getRowByKey(rowKey, initData);
    let isContinue = true;
    let tipMessage = '';
    columns.forEach(item => {
      let key = item.dataIndex;
      if (target[key] === undefined || target[key] === null){
        switch (key) {
          case "lowerLimit":
            isContinue = false;
            tipMessage = '基数下限不能为空！';
            break;
          case "orgRate":
            if (target.orgFixedAmount === undefined || target.orgFixedAmount === null){
              tipMessage = '公司缴纳比例与公司固定缴纳金额不能都为空！';
              isContinue = false;
            }
            break;
          case "personalRate":
            if (target.personalFixedAmount === undefined || target.personalFixedAmount === null){
              tipMessage = '个人缴纳比例与个人固定缴纳金额不能都为空！';
              isContinue = false;
            }
            break;
          case "securityType":
            isContinue = false;
            tipMessage = '缴纳项目不能为空！';
            break;
          case "upperLimit":
            isContinue = false;
            tipMessage = '基数上限不能为空！';
            break;
        }
      }
    });
    if (!isContinue){
      message.error(tipMessage);
      return;
    }
    if (initData.length > 0){
      let sameItem = initData.find(item => item.securityType === target.securityType);
      if (sameItem && sameItem.key !== rowKey){
        message.error('存在重复缴纳项目，无法保存！');
        return;
      }
    }
    toggleEditable(e, rowKey)
  };

  const cancel = (e, key) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...initData]; // 编辑前的原始数据
    let cacheData = newData.map((item) => {
      if (item.key === key) {
        if (cacheOriginData[key]) {
          const originItem = {...item, ...cacheOriginData[key], editable: false};
          delete cacheOriginData[key];
          setCacheOriginData(cacheOriginData);
          return originItem
        }
          return null
      }
      return item
    });
    onChange(cacheData.filter(item => item !== null));
    setClickedCancel(false)
  };

  const addPlan = () => {
    const newData = initData?.map((item) => ({ ...item })) || []
    newData.push({
      key: `NEW_TEMP_ID_${index}`,
      editable: true,
      isNew: true,
      orgFormat: 1,
      personalFormat: 1
    });
    setIndex(index + 1);
    onChange(newData);
  };

  return (
    <div id='area'>
      <Table
        loading={loading}
        columns={columns}
        dataSource={initData}
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
      />
      <Button
        style={{
          width: '100%',
          marginTop: 16,
          marginBottom: 8,
        }}
        type="dashed"
        onClick={addPlan}
      >
        <PlusOutlined/>
        新增方案子项
      </Button>
    </div>
  )
};

export default connect(({  }) => ({

}))(TableForm)

